package com.liuke.study.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * TODO
 *
 * @author wangjwy
 * @date 2019/10/22 19:24
 * @since 1.0.0
 */
public class Test7 {

	public static void main(String[] args) throws InterruptedException {
		Lock lock = new ReentrantLock();
		Condition condition = lock.newCondition();
		new Thread(new Work17(lock, condition)).start();
		Thread.sleep(100);
		new Thread(new WorkA7(lock, condition)).start();
		Thread.sleep(3000);
	}

}

class Work17 implements Runnable {
	/**
	 * print 1-52
	 */

	private int count = 0;

	private Lock lock;

	private Condition condition;

	public Work17(Lock lock, Condition condition) {
		this.lock = lock;
		this.condition = condition;
	}

	@Override
	public void run() {
		try {
			lock.tryLock();
			while (count <= 50) {
				System.out.print(++count);
				System.out.print(++count);
				condition.signal();
				try {
					condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			condition.signalAll();
		} finally {
			lock.unlock();
		}

	}
}

class WorkA7 implements Runnable {
	/**
	 * print 1-52
	 */

	private char count = 'A';

	private Lock lock;

	private Condition condition;

	public WorkA7(Lock lock, Condition condition) {
		this.lock = lock;
		this.condition = condition;
	}

	@Override
	public void run() {
		try {
			lock.tryLock();
			while (count <= 'Z') {
				System.out.print(count++);
				System.out.print(" ");
				condition.signal();
				try {
					condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			condition.signalAll();
		} finally {
			lock.unlock();
		}

	}
}